﻿#region Copyright

// The contents of this file are subject to the Mozilla Public License
//  Version 1.1 (the "License"); you may not use this file except in compliance
//  with the License. You may obtain a copy of the License at
//  
//  http://www.mozilla.org/MPL/
//  
//  Software distributed under the License is distributed on an "AS IS"
//  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//  License for the specific language governing rights and limitations under 
//  the License.
//  
//  The Initial Developer of the Original Code is Robert Smyth.
//  Portions created by Robert Smyth are Copyright (C) 2008.
//  
//  All Rights Reserved.

#endregion

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;


namespace NUnitGrid.Protocol
{
    public class ProtocolMessageParser : IProtocolMessageParsing
    {
        private readonly string message;

        public ProtocolMessageParser(string message)
        {
            this.message = message;
        }

        public string GetValue(string propertyName)
        {
            var value = ParseString(string.Format(".*{0}=(?<value>[^\n]+?)$", propertyName));
            if (value == "{")
            {
                var pattern = string.Format(".*{0}={{\r\n(?<value>.*?)\r\n   }}", propertyName);
                value = ParseString(pattern);
                if (value != string.Empty)
                {
                    var lines = value.Split('\r');
                    var cleanedLines = new List<string>();
                    foreach (var line in lines)
                    {
                        var cleanedLine = line.TrimStart('\n', '\r').TrimEnd('\n', '\r');
                        cleanedLine = cleanedLine.Remove(0, Math.Min("   ".Length, cleanedLine.Length));
                        cleanedLines.Add(cleanedLine);
                    }
                    value = string.Join("\n", cleanedLines.ToArray());
                }
            }
            return value;
        }

        public string[] GetPropertyNames()
        {
            var regex = new Regex(".*?\n[ \t]+(?<propertyName>[^:b]+?)=[^\n]+?$",
                                  RegexOptions.Multiline | RegexOptions.Singleline);
            var matches = regex.Matches(message);

            var propertyNames = new List<string>();
            foreach (Match match in matches)
            {
                propertyNames.Add(match.Groups["propertyName"].Value.Trim('\r'));
            }
            return propertyNames.ToArray();
        }

        public int GetTransactionID()
        {
            return int.Parse(ParseString(@"^.*?\((?<value>[^\)]+).*"));
        }

        private string ParseString(string pattern)
        {
            var regex = new Regex(pattern, RegexOptions.Multiline | RegexOptions.Singleline);
            var match = regex.Match(message);
            var group = match.Groups["value"];
            return group.Success ? group.Value.Trim('\r') : string.Empty;
        }
    }
}